<template>
  <div class="home">
    <h2>水果列表</h2>
    <ul>
      <li v-for="fruit in getFruits" :key="fruit.id">
        {{ fruit.name }} - ￥{{ fruit.price }}
        <button @click="addToCart12(fruit)">加入购物车</button>
      </li>
    </ul>

    <h2>购物车</h2>
    <ul>
      <li v-for="item in cart" :key="item.id">
        {{ item.name }} x {{ item.quantity }} - ￥{{ item.price * item.quantity }}
      </li>
    </ul>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex';

export default {
  computed: {
    // 使用 mapGetters 简化获取 getters
    ...mapGetters(['getFruits', 'getCart']),
    
    // 保留 this.$store.getters 的写法
    fruits() {
      return this.$store.getters.getFruits;
    },
    cart() {
      return this.$store.getters.getCart;
    }
  },
  methods: {
    ...mapMutations(['addToCart12']),
    //等价于：
   //   addToCart12(payload) {
   // this.$store.commit('addToCart12', payload);
   //}
    addToCart(fruit) {
      this.$store.dispatch('addToCart', fruit);
    }
  }
}
</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
}

button {
  margin-left: 10px;
}
</style>